package com.lavegue.webaction;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.lavegue.common.Constants;
import com.lavegue.common.ListAction;
import com.lavegue.common.SystemConfig;
import com.lavegue.model.TopUp;
import com.lavegue.model.UserInfo;
import com.lavegue.service.TopUpService;
import com.lavegue.service.UserInfoService;
import com.lavegue.util.PayRequestHandler;
import com.lavegue.util.PayResponseHandler;
import com.lavegue.util.TenpayUtil;
import com.lavegue.util.TopupUtil;


/**
 * author: tinazhifen
 * description:
 *
 */
public class TopUpAction extends ListAction<TopUp> {
	  private BigDecimal payNum;
	  private TopUpService topUpService;
	  private UserInfoService userInfoService;
	  private TopUp detailTopUp;
	  private int payStatus;
	  private int bankType;
	  private int userid;
	public TopUp getDetailTopUp() {
		return detailTopUp;
	}

	
	public int getUserid() {
		return userid;
	}


	public void setUserid(int userid) {
		this.userid = userid;
	}


	public void setDetailTopUp(TopUp detailTopUp) {
		this.detailTopUp = detailTopUp;
	}

	//确定充值
	public String addTopUp()
	{
		if (this.getSessionUser() == null) {
			return G_LOGIN_PAGE; 
		}
		detailTopUp = new TopUp();
		detailTopUp.setSum(payNum);
		detailTopUp.setMsgNum(TopupUtil.getMsgCntByPrice(payNum));
//		TopUp topup=new TopUp();
//		topup.setTopupTime(new Date());
//		UserInfo user= userInfoService.findById(this.getSessionUser().getId());
//		if(null!=user)
//		{
//			topup.setUserInfo(user);
//		}
//		//topup.setBalance(user.getBalance().add(payNum));
//		topup.setSum(payNum);
//		topUpService.save(topup);
//		detailTopUp=topup;
		return "sendPayNext";
	}
	
	 /**
	  * 银行转账
	 * @return
	 */
	public String sendPayWzz()
	 {
		detailTopUp = new TopUp();
		detailTopUp.setSum(payNum);
		detailTopUp.setMsgNum(TopupUtil.getMsgCntByPrice(payNum));
		 return "sendPayWszzS";
	 }
	 
	/**
	 * 跳转到财付通支付页面
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public String gotoCftPayPage() throws UnsupportedEncodingException {
		return "cftPayPage";
	}
	
	/**
	 * 显示财付通支付的结果,保存数据到数据库
	 * @return
	 */
	public String showCftPayResult() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		//密钥
		String key = SystemConfig.getSecretKey();

		//创建PayResponseHandler实例
		PayResponseHandler resHandler = new PayResponseHandler(request, response);

		resHandler.setKey(key);

		//交易单号
		String transactionId = resHandler.getParameter("transaction_id");
		
		//金额金额,以分为单位
		String total_fee = resHandler.getParameter("total_fee");
		
		//支付结果
		String pay_result = resHandler.getParameter("pay_result");
		this.detailTopUp = new TopUp();
		this.detailTopUp.setSum(new BigDecimal(total_fee).divide(new BigDecimal("100")));
		detailTopUp.setMsgNum(TopupUtil.getMsgCntByPrice(detailTopUp.getSum()));
		//判断签名
		if(resHandler.isTenpaySign()) {
//		if(true) {
			//支付成功
			if( "0".equals(pay_result) ) {
				//------------------------------
				//处理业务开始
				//------------------------------ 
				UserInfo user = userInfoService.findById(this.getSessionUser().getId());
				TopUp t = new TopUp();
				t.setUserInfo(user); 
				//充值类型,1: 财付通2，银行转账
				t.setTopupType(TopUp.TOPUP_TYPE_CFT);
				t.setTopupTime(new Date());
				t.setSum(new BigDecimal(total_fee).divide(new BigDecimal("100")));
				t.setMsgNum(TopupUtil.getMsgCntByPrice(t.getSum()));
				t.setRemainNum(t.getMsgNum());
				t.setTransactionId(transactionId);
				t.setAccRemain(user.getMsgCnt() + t.getMsgNum());
				topUpService.save(t);
				user.setMsgCnt(t.getAccRemain());
				if (t.getSum().compareTo(new BigDecimal(Constants.VIP)) >=0) {
					user.setType(1);
				}
				userInfoService.update(user);
				this.setSessionAtrribute(Constants.SESSION_USER, user);
				//注意交易单不要重复处理
				//注意判断返回金额
				
				//------------------------------
				//处理业务完毕
				//------------------------------
					
				//调用doShow, 打印meta值跟js代码,告诉财付通处理成功,并在用户浏览器显示$show页面.
//				resHandler.doShow("http://localhost:8080/tenpay/show.jsp");
				payStatus = 1;
				this.setSessionAtrribute("payStatus", payStatus);
			} else {
				//当做不成功处理
				//out.println("支付失败");
				System.out.println("支付失败");
				this.addActionError("支付失败");
			}
			
		} else {
			//out.println("认证签名失败");
			//String debugInfo = resHandler.getDebugInfo();
			//System.out.println("debugInfo:" + debugInfo);
			System.out.println("认证签名失败");
			this.addActionError("认证签名失败");
		}
		return "cftPayResult";
	}
	
	/**
	 * 发送财付通支付请求
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public String sendCftRequest() throws UnsupportedEncodingException {
		this.removeSession("payStatus");
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		
		// 商家的商户号,有腾讯公司唯一分配
		String bargainor_id = SystemConfig.getbargainorId();

		//密钥
		String key = SystemConfig.getSecretKey();	

		//回调通知URL
		String return_url = SystemConfig.getReturnUrl();

		//当前时间 yyyyMMddHHmmss
		String currTime = TenpayUtil.getCurrTime();

		//8位日期
		String strDate = currTime.substring(0, 8);

		//6位时间
		String strTime = currTime.substring(8, currTime.length());

		//四位随机数
		String strRandom = TenpayUtil.buildRandom(4) + "";

		//10位序列号,可以自行调整。
		String strReq = strTime + strRandom;

		//商家订单号,长度若超过32位，取前32位。财付通只记录商家订单号，不保证唯一。
		String sp_billno = strReq;

		//财付通交易单号，规则为：10位商户号+8位时间（YYYYmmdd)+10位流水号
		String transaction_id = bargainor_id + strDate + strReq;

		//创建PayRequestHandler实例
		PayRequestHandler reqHandler = new PayRequestHandler(request, response);

		//设置密钥
		reqHandler.setKey(key);

		//初始化
		reqHandler.init();

		//-----------------------------
		//设置支付参数
		//-----------------------------
		reqHandler.setParameter("bargainor_id", bargainor_id);			//商户号
		reqHandler.setParameter("sp_billno", sp_billno);				//商家订单号
		reqHandler.setParameter("transaction_id", transaction_id);		//财付通交易单号
		reqHandler.setParameter("return_url", return_url);				//支付通知url
		reqHandler.setParameter("desc", "订单号：" + transaction_id);	//商品名称
//		reqHandler.setParameter("total_fee", "1");						//商品金额,以分为单位
		reqHandler.setParameter("total_fee", (payNum.multiply(new BigDecimal("100"))) + "");						//商品金额,以分为单位
		reqHandler.setParameter("bank_type", "0");			//银行类型， 0是财付通
		
		//用户ip,测试环境时不要加这个ip参数，正式环境再加此参数
		reqHandler.setParameter("spbill_create_ip",request.getRemoteAddr());

		//获取请求带参数的url
		String requestUrl = reqHandler.getRequestURL();

		//获取debug信息
		String debuginfo = reqHandler.getDebugInfo();
		this.setRequestAtrribute("requestUrl", requestUrl);
		System.out.println("requestUrl:" + requestUrl);
		System.out.println("debuginfo:" + debuginfo);
		//去页面那执行跳转
		return "executePage";
	}
	 
	 /**
	  * 财付通
	 * @return
	 */
	public String sendPayCft()
	 {
		 return "sendPaycft";
	 }
	
	
	/**
	 * 确认付款
	 * @return
	 */
	public String confirmPay() {
		this.detailTopUp = new TopUp();
		this.detailTopUp.setSum(payNum);
		detailTopUp.setMsgNum(TopupUtil.getMsgCntByPrice(detailTopUp.getSum()));
		return "confirmPay";
	}
	 
	public String adminTopup() {
		TopUp t = new TopUp();
		UserInfo user = userInfoService.findById(userid);
		t.setUserInfo(user); 
		//充值类型,1: 财付通2，银行转账
		t.setTopupType(TopUp.TOPUP_TYPE_WY);
		t.setTopupTime(new Date());
		t.setSum(payNum);
		t.setMsgNum(TopupUtil.getMsgCntByPrice(t.getSum()));
		t.setRemainNum(t.getMsgNum());
		t.setTransactionId("");
		t.setAccRemain(t.getUserInfo().getMsgCnt() + t.getMsgNum());
		topUpService.save(t);
		user.setMsgCnt(t.getAccRemain());
		if (t.getSum().compareTo(new BigDecimal(Constants.VIP)) >=0) {
			user.setType(1);
		}
		userInfoService.update(user);
		return "userList";
	}

	public int getPayStatus() {
		return payStatus;
	}

	public void setPayStatus(int payStatus) {
		this.payStatus = payStatus;
	}

	public BigDecimal getPayNum() {
		return payNum;
	}

	public void setPayNum(BigDecimal payNum) {
		this.payNum = payNum;
	}

	public TopUpService getTopUpService() {
		return topUpService;
	}

	public void setTopUpService(TopUpService topUpService) {
		this.topUpService = topUpService;
	}

	public UserInfoService getUserInfoService() {
		return userInfoService;
	}

	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}

	public int getBankType() {
		return bankType;
	}

	public void setBankType(int bankType) {
		this.bankType = bankType;
	}
		
}

